import React, { useState, useEffect, useRef, act } from 'react';
import { ProTable, PageContainer, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Drawer, Button, message, Popconfirm, Descriptions,Image } from 'antd';
import { deleteClientUser, fetchClientUserList, createClientUser, updateClientUser,detailUser } from '@/services/ant-design-pro/user';

const UserList = () => {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [loading, setLoading] = useState(false);
  const [form] = ProForm.useForm();
  const actionRef = useRef();
  const [activeKey, setActiveKey] = useState<string>('');

  const handleEdit = async (record) => {
    const deatil = await detailUser(record.id);
    setCurrentRecord(deatil.data);
    console.log(currentRecord,'--currentRecord')
    form.setFieldsValue(record);
    setDrawerVisible(true);
  };

  const handleAdd = () => {
    setCurrentRecord(null);
    form.resetFields();
    setDrawerVisible(true);
  };

  const handleFinish = async (values) => {
    try {
      if (currentRecord) {
        // 编辑
        const response = await updateClientUser({ ...currentRecord, ...values });
        if (response.code === '1') {
          message.success('修改成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }
      } else {
        // 添加
        const response = await createClientUser(values);
        if (response.code === '1') {
          message.success('添加成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }
      }
    } catch (error) {
      message.error('操作失败');
    } finally {
      setDrawerVisible(false);
    }
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteClientUser({ id });
      if (response) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns = [
   
    {
      title: '用户类型',
      dataIndex: 'userType',

     valueEnum: {
        0: {text: '个人'},
        1: {text: '企业'}
      }
      ,
      search:false
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      render: (text, record) => <a onClick={() => handleEdit(record)}>{text}</a>,
    }, 
    {
      title: '用户名',
      dataIndex: 'loginId',
      hidden:true,
      search:false
    },
 
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      hidden: activeKey === '0' ? true : false,
      search:activeKey === '0' ? false : true
    },
    {
      title: '用户ID',
      dataIndex: 'id',
      valueType: 'digit'
    },
    {
      title: '用户编码',
      dataIndex: 'userCode',
    },
    {
      title: '电子邮箱',
      dataIndex: 'email',
      search:false
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      search:false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => handleEdit(record)}>
          查看
        </a>
      //     <Popconfirm
      //     key="delete"
      //     title="确定删除该项吗？"
      //     onConfirm={(event) => {
      //         event.stopPropagation();
      //         handleDelete(record.id)
      //     }}
      //     onCancel={(event) => {
      //         event.stopPropagation(); // 阻止事件冒泡
      //     }}
      // >
      //   <a key="delete">
      //     删除
      //   </a>
      //   </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer header={{title:''}}>
      <ProTable
        columns={columns}
        rowKey="id"
        request={ (params)=> fetchClientUserList({...params,userType:activeKey,id:+params.id})}
        loading={loading}
        search={{
          labelWidth: 'auto',
        }}
        actionRef={actionRef}
        toolBarRender={() => [
          // <Button key="add" type="primary" onClick={handleAdd}>
          //   新增用户
          // </Button>,
        ]}

        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "", label: <span>全部</span> },
              { key: "0", label: <span>个人</span> },
              { key: "1", label: <span>企业</span> },
      
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
      />
      <Drawer
        title={currentRecord ? '查看用户' : '新增用户'}
        width={400}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Descriptions column={1} title="用户信息" bordered style={{ marginTop: 24 }} layout="vertical">

              {/* 根据 userType 显示不同的内容 */}
              {currentRecord?.userType == 0 && (
                <>
              <Descriptions.Item label="用户类型">个人用户</Descriptions.Item>
              <Descriptions.Item label="姓名">{currentRecord?.userName || '-'}</Descriptions.Item>
              <Descriptions.Item label="电子邮箱">{currentRecord?.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="手机号码">{currentRecord?.mobile || '-'}</Descriptions.Item>
                </>
              )}

              {currentRecord?.userType == 1 && (
                <>
                  <Descriptions.Item label="用户类型">企业用户</Descriptions.Item>
                  <Descriptions.Item label="企业名称">{currentRecord?.companyName || '-'}</Descriptions.Item>
                  {/* <Descriptions.Item label="企业法人">{currentRecord?.companyLegal || '-'}</Descriptions.Item> */}
                  <Descriptions.Item label="营业执照">
                  <Image width={100} src={currentRecord?.businessLicense}></Image>
                  </Descriptions.Item>
                  <Descriptions.Item label="统一社会信用代码">{currentRecord?.societyCreditCode || '-'}</Descriptions.Item>
                  <Descriptions.Item label="企业地址">{currentRecord?.companyAddressName || '-'}</Descriptions.Item>
                  <Descriptions.Item label="详细地址">{currentRecord?.companyAddressDetail || '-'}</Descriptions.Item>
                  <Descriptions.Item label="联系电话">{currentRecord?.mobile || '-'}</Descriptions.Item>
                  <Descriptions.Item label="联系人">{currentRecord?.userName || '-'}</Descriptions.Item>
                  <Descriptions.Item label="邮箱">{currentRecord?.email || '-'}</Descriptions.Item>
                </>
              )}

              {/* 其他通用信息 */}
              <Descriptions.Item label="创建时间">{currentRecord?.createTime || '-'}</Descriptions.Item>
              {/* <Descriptions.Item label="状态">{currentRecord?.prOnoff === 1 ? '启用' : '停用'}</Descriptions.Item> */}
            </Descriptions>
      </Drawer>
    </PageContainer>
  );
};

export default UserList;
